package com.ruoyi.business.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.business.mapper.WsdRefundTransactionsMapper;
import com.ruoyi.business.service.IWsdRefundTransactionsService;
import com.ruoyi.common.core.domain.dto.WsdPaymentRecordsDTO;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.WsdRefundTransactions;
import com.ruoyi.common.core.domain.vo.ChartDataVO;
import com.ruoyi.common.core.domain.vo.WsdRefundTransactionsVO;
import com.sun.xml.bind.v2.TODO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;

/**
 * <p>
 * 退款流水表，记录所有退款相关的信息 服务实现类
 * </p>
 *
 * @author wwq
 * @since 2024-05-20
 */
@Service
public class WsdRefundTransactionsServiceImpl extends ServiceImpl<WsdRefundTransactionsMapper, WsdRefundTransactions> implements IWsdRefundTransactionsService {
    @Autowired
    private WsdRefundTransactionsMapper wsdRefundTransactionsMapper;


    @Override
    public List<WsdRefundTransactions> selectWsdRefundTransactionsList(WsdRefundTransactions wsdRefundTransactions)
    {
        return wsdRefundTransactionsMapper.selectWsdRefundTransactionsList(wsdRefundTransactions);
    }

    @Override
    public List<WsdRefundTransactionsVO> listRefund(WsdPaymentRecordsDTO wsdPaymentRecordsDTO) {
        SysUser user = getLoginUser().getUser();
        Long schoolId = user.getSchoolId();
        wsdPaymentRecordsDTO.setStatus(2);
        if (!user.isAdmin()) {
            if (wsdPaymentRecordsDTO.getSchoolsId()==null) {
                wsdPaymentRecordsDTO.setSchoolsId( schoolId );
            }
        }
        // 处理时间范围
        if (wsdPaymentRecordsDTO.getType() != null) {
            LocalDate today = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            switch (wsdPaymentRecordsDTO.getType()) {
                case 0: // 今天
                    wsdPaymentRecordsDTO.setRechargeTimeStart(today.atStartOfDay().format(formatter));
                    wsdPaymentRecordsDTO.setRechargeTimeEnd(today.atTime(23, 59, 59).format(formatter));
                    break;
                case 1: // 本周
                    LocalDate startOfWeek = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
                    LocalDate endOfWeek = today.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
                    wsdPaymentRecordsDTO.setRechargeTimeStart(startOfWeek.atStartOfDay().format(formatter));
                    wsdPaymentRecordsDTO.setRechargeTimeEnd(endOfWeek.atTime(23, 59, 59).format(formatter));
                    break;
                case 2: // 本月
                    LocalDate startOfMonth = today.with(TemporalAdjusters.firstDayOfMonth());
                    LocalDate endOfMonth = today.with(TemporalAdjusters.lastDayOfMonth());
                    wsdPaymentRecordsDTO.setRechargeTimeStart(startOfMonth.atStartOfDay().format(formatter));
                    wsdPaymentRecordsDTO.setRechargeTimeEnd(endOfMonth.atTime(23, 59, 59).format(formatter));
                    break;
                case 3: // 自定义时间, 前端直接传入
                    // 已经由前端设置好，无需处理
                    break;
                default:
                    throw new IllegalArgumentException("无效的日期类型");
            }
        }

        // 调用MyBatis查询
        return wsdRefundTransactionsMapper.listRefund(wsdPaymentRecordsDTO);
    }

    @Override
    public ChartDataVO getTotalFeeByDateRange(String startDate, String endDate) {
        List<Map<String, Object>> refundData = wsdRefundTransactionsMapper.getTotalFeeByDateRange(startDate,endDate);
        return processRefundData(refundData, 2, startDate, endDate);
    }

    @Override
    public ChartDataVO getTotalFeeByYear() {
        int currentYear = LocalDate.now().getYear();
        List<Map<String, Object>> refundData = wsdRefundTransactionsMapper.getTotalFeeByMonth(currentYear);
        return processRefundData(refundData, 1);
    }

    @Override
    public ChartDataVO getTotalFeeByMonth() {
        int currentYear = LocalDate.now().getYear();
        List<Map<String, Object>> refundData = wsdRefundTransactionsMapper.getTotalFeeByMonth(currentYear);
        return processRefundData(refundData, 0);
    }

    private ChartDataVO processRefundData(List<Map<String, Object>> refundData, int queryType) {
        return processRefundData(refundData, queryType, null, null);
    }


    private ChartDataVO processRefundData(List<Map<String, Object>> refundData, int queryType, String startDate, String endDate) {
        List<String> labels = new ArrayList<>();
        List<Integer> values = new ArrayList<>();
        int totalAmount = 0;

        if (queryType == 0) {
            // 初始化12个月的值
            for (int i = 1; i <= 12; i++) {
                labels.add(i + "月");
                values.add(0);
            }
        } else if (queryType == 1) {
            // 初始化当前年的每月值
            int currentYear = LocalDate.now().getYear();
            for (int i = 1; i <= 12; i++) {
                labels.add(currentYear + "-" + (i < 10 ? "0" + i : i));
                values.add(0);
            }
        } else if (queryType == 2) {
            // 初始化自定义时间区间的每日值
            LocalDate start = LocalDate.parse(startDate);
            LocalDate end = LocalDate.parse(endDate);
            while (!start.isAfter(end)) {
                labels.add(start.toString());
                values.add(0);
                start = start.plusDays(1);
            }
        }
        //TODO 退款流水统计
        for (Map<String, Object> data : refundData) {
            String period = (String) data.get("period");
            int totalRefundAmount = ((Number) data.get("totalRefundAmount")).intValue();

            if (queryType == 0 || queryType == 1) {
                int month = Integer.parseInt(period.split("-")[1]);
                values.set(month - 1, totalRefundAmount);
            } else {
                int index = labels.indexOf(period);
                if (index != -1) {
                    values.set(index, totalRefundAmount);
                }
            }

            totalAmount += totalRefundAmount;
        }

        ChartDataVO refundChartData = new ChartDataVO();
        refundChartData.setLabels(labels);
        refundChartData.setValues(values);
        refundChartData.setTotalAmount(totalAmount);

        return refundChartData;
    }
}
